/**
 * 
 */
package client;


import java.io.Serializable;
import java.rmi.RemoteException;

import server.TweetStack;
import common.Tweet;


/**
 * @author Machado
 *
 */
public class ClientServer implements ClientInterface, Runnable, Serializable {
	
	private TweetStack stack;
	private TweetStack pool;
	
	
	public ClientServer(TweetStack stack){
		this.stack = stack;
		this.pool = new TweetStack();
	}
	
	/* (non-Javadoc)
	 * @see client.ClientInterface#addTweet(common.Tweet)
	 */
	
	@Override
	public synchronized void addTweet(Tweet tweet) throws RemoteException {	
		stack.push(tweet);
		System.out.println("Chegou o tweet  "+tweet.getId()+"  status  "+tweet.getMsg());		
	}

	/* (non-Javadoc)
	 * @see client.ClientInterface#getTweets()
	 */
	@Override
	
	public TweetStack getTweets(Tweet last) throws RemoteException {
		TweetStack ret = new TweetStack(pool);
		if (isLatest(last, ret)){
			return null;
		}	
		return ret;
		
	}


	public boolean isLatest(Tweet tweet, TweetStack stack){
		int range = stack.getStack().size();
		if (range == 0){
			return true;
		}
		long id1 = tweet.getId();
		long id2 = pool.get(range-1).getId();
		if (id1 == id2){
			return true;
		}
		else{
			return false;
		}
	}

	
	/* (non-Javadoc)
	 * @see client.ClientInterface#isAlive()
	 */
	@Override
	public void isAlive() throws RemoteException {
		
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		while(true){
			try {
				System.out.println("Sleeping");
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				continue;
			}
			System.out.println("Swaping");
			swap();
		}
		
	}
	
	public synchronized void swap(){
		pool = new TweetStack (stack);
		stack = new TweetStack ();		
	}

}
